package com.guinea.account.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessages;
import org.springframework.util.ReflectionUtils;

import com.guinea.account.entity.Contact;
import com.guinea.account.entity.Role;
import com.guinea.account.entity.User;
import com.guinea.account.form.RegisterForm;
import com.guinea.account.service.ContactManager;
import com.guinea.account.service.RoleManager;
import com.guinea.account.service.UserManager;
import com.guinea.core.Constants;
import com.guinea.core.exception.BusinessException;
import com.guinea.core.orm.BaseEntity;
import com.guinea.core.utils.CommonUtils;
import com.guinea.core.utils.StringUtils;
import com.guinea.core.web.StrutsAction;

public class RegisterAction extends StrutsAction {
	private UserManager userManager;
	private ContactManager contactManager;
	private RoleManager roleManager;
	public UserManager getUserManager() {
		return userManager;
	}


	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public ContactManager getContactManager() {
		return contactManager;
	}


	public void setContactManager(ContactManager contactManager) {
		this.contactManager = contactManager;
	}


	public RoleManager getRoleManager() {
		return roleManager;
	}


	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}


	/**
	 * url参数未定义method时的默认Action函数. 默认为index Action.
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return edit(mapping, form, request, response);
	}

	/**
	 * 显示修改对象Form的Action函数.
	 */
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// 防止重复提交的token
		saveToken(request);

		return mapping.findForward("edit");
	}

	/**
	 * 保存对象的Action函数.
	 */
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		//验证TOKEN，防止重复提交
		if(!validateToken(request)) return mapping.findForward("edit");
		
		User user = new User();
		
		//save操作前的验证
		ActionMessages errors = form.validate(mapping, request);
		if (!errors.isEmpty()) {
			saveErrors(request, errors);
			resetToken(request);
			return edit(mapping, form, request, response);
		}
		RegisterForm registerForm = (RegisterForm)form; 
		String loginName = registerForm.getLoginName();
		List us = getUserManager().getUsersByName(loginName);
		if(us!=null && us.size()>0) {
			saveDirectlyError(request, "用户名 " + loginName + " 已存在。" );
			resetToken(request);
			return edit(mapping, form, request, response);
		}
		try {
			// 将registerform内容绑定到user
			bindEntity(form,user);
			//为保存操作添加创建人更新人等信息
			addCrudData(user);
//			user.setStatus(Constants.STATUS_INVALID);
			if(StringUtils.isBlank(user.getOtherName()))
				user.setOtherName(user.getLoginName());
			//取得user权限的，
			Role role = null;
			List rl = getRoleManager().getRolesByName("user");
			if(rl != null && rl.size() > 0) role = (Role)rl.get(0);
			if(role != null) user.getRoles().add(role);
			getUserManager().saveUser(user);
			Contact contact = new Contact();
			// 将registerform内容绑定到contact
			bindEntity(form,contact);
			//为保存操作添加创建人更新人等信息
			addCrudData(contact);
			contact.setUser(user);
			getContactManager().save(contact);
			savedMessage(request);
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			saveDirectlyError(request, e.getMessage());
			return edit(mapping, form, request, response);
		}
		return mapping.findForward(SUCCESS);
	}
	
	/**
	 * 生成保存成功的信息.
	 */
	protected void savedMessage(HttpServletRequest request) {
		saveMessage(request, "entity.saved");
	}
	/**
	 * 为保存操作添加创建人更新人等信息，保存操作专用
	 * @param isNewEntity 是否创建新对象
	 * @param object
	 * @return
	 */
	protected BaseEntity addCrudData(Object object){
		//保存创建人更新人
		BaseEntity baseEntity = (BaseEntity) object;
		Long userId = CommonUtils.getCurrentUserId();
		//注册用户
		if(userId == null) userId = new Long(0);
		baseEntity.setStatus(Constants.STATUS_VALID);
		baseEntity.setCreator(userId);
		baseEntity.setCreated(new Date());

		return baseEntity;
	}
	
	/**
	 * 将FormBean中的内容通过BeanUtils的copyProperties()绑定到Object中. 因为BeanUtils中两个参数的顺序很容易搞错，因此封装此函数.
	 */
	protected void bindEntity(ActionForm form, Object object) {
		if (form != null) {
			try {
				BeanUtils.copyProperties(object, form);
			} catch (Exception e) {
				ReflectionUtils.handleReflectionException(e);
			}
		}
	}
	/**
	 * 验证TOKEN
	 * @param request
	 * @return
	 */
	protected boolean validateToken(HttpServletRequest request){
		if (isCancelled(request))
			return false;
		if (!isTokenValid(request)) {
			saveDirectlyError(request, "重复提交");
			return false;
		}
		resetToken(request);
		return true;
	}
}
